package com.base.controller.redisTest;

import com.base.po.voip.SelfShopGoods;
import com.base.service.SelfShopGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

@Controller
@RequestMapping("/redis")
public class redisTestFor {
    @Autowired
    SelfShopGoodsService selfShopGoodsService;
    @RequestMapping("/redder")
    @ResponseBody
    public String  redder() {

       synchronized (this){
           SelfShopGoods s= selfShopGoodsService.selectByPrimaryKey("1");
          Integer s2= s.getStock();
           System.out.println("当前库存:"+s2);
           if (s2>0){
               s.setStock(s2-1);
               selfShopGoodsService.updateByPrimaryKeySelective(s);
           }else {
               System.out.println("库存不够了");
           }
           return s2.toString();
       }
    }

    /**
     * @Date: 2019/11/13 11:26
     * @Description: 将数据库中的商品库存放入redis中
     */
    @RequestMapping("/put")
    @ResponseBody
    public String putShopGoods() {
        List<SelfShopGoods> list=selfShopGoodsService.selectAllStock();
        Enumeration<SelfShopGoods> e = Collections.enumeration(list);
        JedisPool jedisPool=new JedisPool();
        Jedis jedis=jedisPool.getResource();
        System.out.println("开始将数据读入redis");
        while (e.hasMoreElements()){
            if (e.nextElement()!=null){
                System.out.println("读取一次");
                SelfShopGoods selfShopGoods=e.nextElement();
                jedis.set("SELFSHOPGOODS:"+selfShopGoods.getId(),selfShopGoods.getStock().toString());
                System.out.println(selfShopGoods.getGoodstext());
            }
        }
        //返回结果
        return "ok";
    }


}
